//
//  SAPirntShopAllocateIn.m
//  saasRetail
//
//  Created by 黄志刚 on 2022/4/25.
//

#import "SAPirntShopAllocateIn.h"
#import "SASalesOrderViewListModel.h"
#import "SACommoditySpecialFeesModel.h"
#import "NSString+Print.h"
#import "SAAllocateDetailModel.h"

@interface SAPirntShopAllocateIn ()

@property (nonatomic, strong) NSArray *typographyArr;
@property (nonatomic, assign) BOOL isHongKong;

@end

@implementation SAPirntShopAllocateIn
+ (void)printWithTotalData:(SAAllocateDetailModel *)allocateDetailModel printSuccessBlock:(SAPrintSuccessBlock)printSuccessBlock {
    static BOOL isFirst = YES;
    
    SAPirntShopAllocateIn *this = [[SAPirntShopAllocateIn alloc] init];
    this.allocateDetailModel = allocateDetailModel;
    this.userInfoModel = [SAValueManger shareInStance].userInfo;
    SACommoditySpecialFeesModel *hkSymbol = [SAOverallSetting shareInstance].hkSymbol;
    this.isHongKong = NO;
    if ([hkSymbol.value isEqualToString:@"1"]) {
        this.isHongKong = YES;
    }
    
    SACommoditySpecialFeesModel *ticketLayoutAttribute = [SAOverallSetting shareInstance].ticketLayoutAttribute;
    NSArray *arr = [ticketLayoutAttribute.value componentsSeparatedByString:@","];
    if (arr.count < 18) {
        arr = [NSArray arrayWithObjects:@"0", @"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",nil];
    }
    this.typographyArr = arr;
    
    [this printStoreName];// 打印标题头
    [this printLineFeed];// 打印换行
    [this printHeader];// 打印头部
    [this printLineFeed];// 打印换行
    
    [this printSku];// 打印sku数据
    [this printTotal];// 打印合计值（入库、退货、应付、实付、欠款、余款等）
    [this printLineFeed];// 打印换行
    
    [this printBottom];// 打印底部（备足、银行卡信息、电话、地址、提示、操作人、公司名称）
    
    [this printLineFeed];// 打印换行
    [this printLineFeed];// 打印换行
    [this printLineFeed];// 打印换行
    [this printLineFeed];// 打印换行
    [this printPaperCut];// 打印剪纸
    
    [[BluetoothManager sharedInstance] writeToPeripheralWithData:this.writeData success:^{
        NSLog(@"商品入库打印：写入成功");
        if (isFirst) {
            isFirst = NO;
            if (printSuccessBlock) {
                printSuccessBlock();
            }
        }
    } failure:^(NSString * _Nonnull errorMessage) {
        NSLog(@"商品入库打印：写入失败：%@",errorMessage);
        dispatch_async(dispatch_get_main_queue(), ^{
            [Prompt popPromptViewWithMsg:errorMessage duration:2];
        });
    }];
}

// 打印店铺名称
- (void)printStoreName {
    NSString *storeName = @"调货单";
    NSData *data = [self.escPrinter printCenterText2:storeName font:(PrinterPrintTextFontMiddle)];;
    [self.writeData appendData:data];
}

// 打印头部（单号、申请店、申请人、申请时间）
- (void)printHeader {
    
    NSString *str1 = [NSString stringWithFormat:@"单号: %@",self.allocateDetailModel.dispatchOrderNo?self.allocateDetailModel.dispatchOrderNo:@""];
    NSData *data1 = [self.escPrinter printText:str1 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    [self.writeData appendData:data1];
    
    NSString *str2 = [NSString stringWithFormat:@"申请店: %@",self.allocateDetailModel.storeName?self.allocateDetailModel.storeName:@""];
    NSData *data2 = [self.escPrinter printText:str2 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    [self.writeData appendData:data2];
    
    NSString *str3 = [NSString stringWithFormat:@"申请人: %@",self.allocateDetailModel.empName?self.allocateDetailModel.empName:@""];
    NSData *data3 = [self.escPrinter printText:str3 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    [self.writeData appendData:data3];
    
    NSString *str4 = [NSString stringWithFormat:@"申请时间: %@",self.allocateDetailModel.dispatchTime?self.allocateDetailModel.dispatchTime:@""];
    NSData *data4 = [self.escPrinter printText:str4 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    [self.writeData appendData:data4];
    
    [self printPartingLine];
    
    NSString *str5 = [NSString stringWithFormat:@"调出店: %@",self.allocateDetailModel.targetStoreName?self.allocateDetailModel.targetStoreName:@""];
    NSData *data5 = [self.escPrinter printText:str5 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    [self.writeData appendData:data5];
    
    if (self.allocateDetailModel.targetEmpName.length > 0) {
        if ([self.allocateDetailModel.dispatchType isEqualToString:@"2"]) {
            NSString *str6 = [NSString stringWithFormat:@"调出人: %@",self.allocateDetailModel.targetEmpName?self.allocateDetailModel.targetEmpName:@""];
            NSData *data6 = [self.escPrinter printText:str6 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
            [self.writeData appendData:data6];
            
            NSString *str7 = [NSString stringWithFormat:@"调出时间: %@",self.allocateDetailModel.receiveTime?self.allocateDetailModel.receiveTime:@""];
            NSData *data7 = [self.escPrinter printText:str7 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
            [self.writeData appendData:data7];
        }else {
            NSString *str6 = [NSString stringWithFormat:@"申请人: %@",self.allocateDetailModel.targetEmpName?self.allocateDetailModel.targetEmpName:@""];
            NSData *data6 = [self.escPrinter printText:str6 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
            [self.writeData appendData:data6];
            
            NSString *str7 = [NSString stringWithFormat:@"申请时间: %@",self.allocateDetailModel.receiveTime?self.allocateDetailModel.receiveTime:@""];
            NSData *data7 = [self.escPrinter printText:str7 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
            [self.writeData appendData:data7];
        }
    }
}

// 打印sku数据
- (void)printSku {
    SAOverallSetting *overallSetting = [SAOverallSetting shareInstance];
    NSInteger printerByteWidth = 48;
    if ([overallSetting.printSize.value isEqualToString:@"0"]) {
        printerByteWidth = 42;
    }
    
    NSMutableArray <SASalesOrderViewListModel *>*productInfoList = [NSMutableArray array];
    for (dispatchDetailModel *model in self.allocateDetailModel.detailVOS) {
        SASalesOrderViewListModel *productModel = [SASalesOrderViewListModel new];
        productModel.productId = model.productId;
        productModel.productCode = model.productCode;
        productModel.productName = model.productName;
        productModel.toPendSkuAttrs = [NSMutableArray array];
        for (dispatchSKUDetailModel *model2 in model.dispatchSKUDetailVOS) {
            SASalesOrderToPendSkuList *list = [SASalesOrderToPendSkuList new];
            list.colourName = model2.color;
            list.sizeName = model2.size;
            list.price = model2.price;
            list.count = model2.count;
            list.subtotal = model2.subtotal;
            [productModel.toPendSkuAttrs addObject:list];
        }
        [productInfoList addObject:productModel];
    }
    
    SAPrintSkuColorSizeLine *printSku = [[SAPrintSkuColorSizeLine alloc] init];
    if ([overallSetting.printSize.value isEqualToString:@"0"]) {
        NSArray *printSkuStrArray = [printSku warehousingPrintSkuColorSizeLineWithProductSkuArray2:productInfoList printerByteWidth:printerByteWidth];
        for (NSData *data in printSkuStrArray) {
            [self.writeData appendData:data];
        }
    }else {
        NSArray *printSkuStrArray = [printSku warehousingPrintSkuColorSizeLineWithProductSkuArray:productInfoList printerByteWidth:printerByteWidth];
        for (NSString *str in printSkuStrArray) {
            NSData *data = [self.escPrinter printText:str font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
            [self.writeData appendData:data];
        }
    }
}

// 打印合计值
- (void)printTotal {
    NSInteger saleCount = 0;
    double saleTotalPrice = 0.f;
    for (dispatchDetailModel *model in self.allocateDetailModel.detailVOS) {
        for (dispatchSKUDetailModel *model2 in model.dispatchSKUDetailVOS) {
            saleCount += [model2.count integerValue];
            saleTotalPrice += [model2.count integerValue] * [model2.price doubleValue]/100;
        }
    }
    NSString *str1 = [NSString stringWithFormat:@"合计: %zd件，%0.2lf元",saleCount,saleTotalPrice];
    if (self.isHongKong == YES) {
        str1 = [NSString stringWithFormat:@"合计: %zd件，%0.2lf港元",saleCount,saleTotalPrice];
    }
    NSData *data1 = [self.escPrinter printText:str1 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    [self.writeData appendData:data1];
    
//    NSString *str2 = [NSString stringWithFormat:@"操作人: %@",self.allocateDetailModel.storeNcreateEmpNameame?self.allocateDetailModel.createEmpName:@""];
//    NSData *data2 = [self.escPrinter printText:str2 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
//    [self.writeData appendData:data2];
//
//    NSString *str3 = [NSString stringWithFormat:@"操作时间: %@",self.allocateDetailModel.receiveTime?self.allocateDetailModel.receiveTime:@""];
//    NSData *data3 = [self.escPrinter printText:str3 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
//    [self.writeData appendData:data3];
}


// 打印底部（备注、银行卡信息、电话、地址、提示、操作人、公司名称）
- (void)printBottom {
    
//    if ([self.typographyArr[15] isEqualToString:@"15"]) {
        NSData *data6 = [self.escPrinter printCenterText2:@"深圳市孚云信息科技有限公司" font:(PrinterPrintTextFontSmall)];
        [self.writeData appendData:data6];

        NSData *data7 = [self.escPrinter printCenterText2:@"衣点通服装管理系统" font:(PrinterPrintTextFontSmall)];
        [self.writeData appendData:data7];
        NSData *data8 = [self.escPrinter printCenterText2:@"客服热线电话:0755-27804689" font:(PrinterPrintTextFontSmall)];
        [self.writeData appendData:data8];
//    }
}

// 打印分割线
- (void)printPartingLine {
    NSData *data = [self.escPrinter printPartingLine:0];
    [self.writeData appendData:data];
}
// 打印换行
- (void)printLineFeed {
    NSData *data = [self.escPrinter lineFeed];
    [self.writeData appendData:data];
}
// 打印剪纸
- (void)printPaperCut {
    NSData *data = [self.escPrinter paperCut];
    [self.writeData appendData:data];
}

-(void)printWordWrap:(NSString *)text {
    SAOverallSetting *overallSetting = [SAOverallSetting shareInstance];
    if ([overallSetting.printSize.value isEqualToString:@"0"]) {
        NSInteger len = [NSString getPrintTextByteTotalWithText:text font:NSStringFontSmall];
        if (len > 32) {
            NSString *newStr = [NSString stringWithFormat:@"%@",text];
            for (int i = 0; i < len; i= i + 32) {
                NSString *str = [newStr getSubStringWithByteWidthMax:32 font:NSStringFontSmall];
                newStr = [newStr substringFromIndex:str.length];
                NSData *data = [self.escPrinter printText:str font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
                [self.writeData appendData:data];
            }
        }else {
            NSData *data = [self.escPrinter printText:text font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
            [self.writeData appendData:data];
        }
    }else {
        NSData *data = [self.escPrinter printText:text font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
        [self.writeData appendData:data];
    }
}

@end
